package com.sunday.android.fangdaifu.bukong.activity.index;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.squareup.picasso.Picasso;
import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.entity.IndexHouseDetail;
import com.sunday.android.fangdaifu.bukong.utils.SelectMapWindow;
import com.sunday.android.fangdaifu.bukong.utils.ShowBigImage;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.member.base.BaseActivity;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
* 地图位置
* */
public class BuilderMapActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.mapView)
    MapView mapView;
    @Bind(R.id.btn_select)
    ImageView btnSelect;
    @Bind(R.id.txt_addr)
    TextView txtAddr;
    private BaiduMap baiduMap;
    private MarkerOptions markerOptions;
    private Marker marker;
    private InfoWindow mInfoWindow;

    private int w;
    private IndexHouseDetail detail;
    private GeoCoder mSearch = GeoCoder.newInstance();
    private String longitude, latitude,oriLatit, oriLongit;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_builder_map);
        ButterKnife.bind(this);
        w = DeviceUtils.getDisplay(mContext).widthPixels;
        detail = (IndexHouseDetail) getIntent().getBundleExtra("detail").getSerializable("detail");
        initView();
    }

    private void initView(){
        latitude =  detail.getLatitude();
        longitude = detail.getLongitude();
        titleView.setText("建筑地址");
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        mLocClient.start();
        updateMapStatus();
        mSearch.setOnGetGeoCodeResultListener(listener);
        mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                        .location(new LatLng(Double.parseDouble(detail.getLatitude()),Double.parseDouble(detail.getLongitude()))));
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker arg0) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.marker_layout,null);
                TextView textView = (TextView)view.findViewById(R.id.name);
                InfoWindow.OnInfoWindowClickListener listener = null;
                final Long id  = (Long)arg0.getExtraInfo().get("pointId");
                String name = (String)arg0.getExtraInfo().get("name");
                if (TextUtils.isEmpty(address)){
                    textView.setText(name);
                }else {
                    textView.setText(address);
                }
                listener = new InfoWindow.OnInfoWindowClickListener() {
                    public void onInfoWindowClick() {
                        baiduMap.hideInfoWindow();
                    }
                };
                LatLng ll = arg0.getPosition();
                baiduMap.hideInfoWindow();
                mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), ll, -50,listener);
                baiduMap.showInfoWindow(mInfoWindow);
                return false;
            }
        });
    }

    private void updateMapStatus(){
        LatLng cenpt ;
        if(!TextUtils.isEmpty(latitude)&&!TextUtils.isEmpty(longitude)){
            cenpt = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
        }else{
            return ;
        }
        //定义地图状态
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .zoom(15)
                .build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        baiduMap.setMapStatus(mMapStatusUpdate);
        drawBitmap(cenpt,1l,detail.getHouseName());
    }

    public void drawBitmap(LatLng latLng,Long pointId,String name){

        //准备 marker 的图片
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding);
        //准备 marker option 添加 marker 使用
        markerOptions = new MarkerOptions().icon(bitmap).position(latLng);
        //获取添加的 marker 这样便于后续的操作
        marker = (Marker) baiduMap.addOverlay(markerOptions);
        Bundle bundle = new Bundle();
        bundle.putLong("pointId",pointId);
        bundle.putString("name",name);
        marker.setExtraInfo(bundle);

    }

    @OnClick(R.id.btn_select)
    void selectMap(){
        SelectMapWindow window=new SelectMapWindow(mContext,oriLatit,oriLongit,latitude,longitude);
        window.showPopupWindow(btnSelect);

    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSearch.destroy();
        if (mapView!=null){
            mapView.onDestroy();
            mapView=null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    private String address;
    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果
            }
            //获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
            }
            //获取反向地理编码结果
            address = result.getAddress();
            txtAddr.setText(address);
        }
    };
    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mapView == null)
                return;
            oriLatit = String.valueOf(location.getLatitude());
            oriLongit = String.valueOf(location.getLongitude());
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }
}
